from util.singelMode import singleton
import json
import os
import sys, getopt
import threading
AppconfigLock = threading.Lock()
@singleton
class CAppconfig:
    def __init__(self):
        self.__config={}
        self.configFromFile = None
        self.configFromCmdLine={}
        self.init()

    def __call__(self):
        return self
    
    def init(self):
        self.configFromCmdLine=self.cmdLineArgsParse(sys.argv[1:])
        netType=self.configFromCmdLine['netType']
        configFilename=f'appconfig-{netType}.json'
        with open(configFilename,'r') as load_f:
            self.configFromFile = json.load(load_f)
        
        
    @property
    def config(self):
        return self.__config

    def setValueBykey(self,key,value):
        self.__config[key]=value


    def getValueByKey(self,key):
        return self.__config[key]
    @staticmethod
    def cmdLineArgsParse(argv):
        cmdlineargs={
            'netType':'mainnet',
            'outputfile':''
        }
        try:
            opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile=","help","testnet"])
        except getopt.GetoptError:
            print('test.py -i <inputfile> -o <outputfile>')
            sys.exit(2)
        for opt, arg in opts:
            if opt in ['-h','--help']:
                print('test.py -i <inputfile> -o <outputfile>')
                sys.exit()
            elif opt =='--testnet':
                cmdlineargs['netType']='testnet'
                
            # elif opt in ("-i", "--ifile"):
            #     cmdlineargs['inputfile'] = arg
            # elif opt in ("-o", "--ofile"):
            #     cmdlineargs['outputfile'] = arg
        return cmdlineargs
    @staticmethod
    def mkdir(path):
        # 去除首位空格
        path=path.strip()
        # 去除尾部 \ 符号
        path=path.rstrip("\\")
    
        # 判断路径是否存在
        # 存在     True
        # 不存在   False
        isExists=os.path.exists(path)
    
        # 判断结果
        if not isExists:
            # 如果不存在则创建目录
            # 创建目录操作函数
            os.makedirs(path) 
    
            # print(path+' 创建成功')
            return True
        else:
            # 如果目录存在则不创建，并提示目录已存在
            # print(path+' 目录已存在')
            return False